package com.cdtu.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdtu.comon.BaseContext;
import com.cdtu.entity.*;

import com.cdtu.mapper.AdminMapper;
import com.cdtu.service.*;
import com.cdtu.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.cdtu.controller.MessageController.CACHE_CERTIFY_KEY;

/**
 * @author : Sakura
 * @Date : 2023/1/10 19:57
 */
@Slf4j
@RestController
//解决跨域问题
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    AdminService adminService;
    @Autowired
    UserService userService;
    @Autowired
    ModulesService modulesService;
    @Autowired
    CertifyService certifyService;
    @Autowired
    CertifyTypeService certifyTypeService;
    @Autowired
    SpecialityService specialityService;
    @Autowired
    SpecialityTypeService specialityTypeService;
    @Autowired
    RUserTaskService rUserTaskService;

    @Autowired
    RUserSpecialityService rUserspecialityService;

    @Autowired
    RUserSpecialityService rUserSpecialityService;

    @Autowired
    RUserCertifyService rUserCertifyService;

    @Autowired
    MessagesService messagesService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    BelongCommunityService belongCommunityService;

   /**
    * 管理员登录方法
    * @return R
    * @author wp
    * @date 2023/1/11 20:12
    */
   @PostMapping("/login")
   public R login( @RequestBody Admin admin) {
       System.out.println(admin);
       String username=admin.getUsername();
       String password = admin.getPassword();
       return adminService.getLogin(username,password);
   }

   //获取社区列表
   @GetMapping("/getCommunity")
   public R getCommunity(){
       List<BelongCommunity> belongCommunityList= belongCommunityService.getAllCommunity();
       return R.success(belongCommunityList);
   }

    /**
     * 管理员注册方法
     * @param admin:
     * @return R
     * @author Sakura
     * @date 2023/1/11 20:11
     */
    @PostMapping("/register")
    public R register(@RequestBody Admin admin) {
        // 对密码加密
        String password=admin.getPassword();
//        password = DigestUtils.md5DigestAsHex(password.getBytes());
        admin.setPassword(password);
        boolean save = adminService.save(admin);
        if (save) {
            // 向超级管理员发送消息 让超级管理员为你分配权限
           Messages message=new Messages();
           message.setIdKey(admin.getId());
           message.setType(0);
           message.setDescription("分配权限");
           message.setTime(new Date());
           messagesService.save(message);

            return R.success();
        }

        else
            return R.error("注册失败");
    }
    /**
    * 根据管理员的id 获取管理员拥有的模块权限
    * @author wp
    * @param id 当前登录管理员的编号
    * @date 2023/1/13 17:36
    * @return
    */
    @GetMapping("/main/model/{id}")
    public R getModules(@PathVariable("id") long id){
            List<AdminModulesVo> modules = modulesService.getModules(id);
            return R.success(modules);
    }
    /**
    * 分页查询管理员列表
    * @author wp
    * @param page 当前页码
    * @param pageSize  每页数据多少
    * @param name  根据管理员的姓名 过滤数据
    * @date 2023/1/13 19:03
    * @return
    */
    @GetMapping("/{page}/{pageSize}")
    public R getAdminList(@RequestParam("name") String name,@PathVariable("page") int page,@PathVariable("pageSize") int pageSize){
        // 分页构造器
        Page pageInfo = new Page<>(page,pageSize);
        // 分页条件
        LambdaQueryWrapper<Admin> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.like(!StrUtil.hasBlank(name),Admin::getName,name);
        // 执行查询
        adminService.page(pageInfo,queryWrapper);
        return  R.success(pageInfo);
    }
    /**
    *  获取所有模块列表
    * @author wp
    * @param
    * @date 2023/1/13 19:05
    * @return
    */
    @GetMapping("/modules")
    public R getAccessList(){
        List<Modules> modules = modulesService.list();
        List<AdminModulesVo> modulesVos=new ArrayList<>();
        for (Modules module : modules) {
            if (module.getParentId() == null){
                List<Modules> child= new ArrayList<>();
                //一级模块
                AdminModulesVo adminModulesVo = new AdminModulesVo();
                BeanUtil.copyProperties(module,adminModulesVo);
                //二级模块
                for (Modules module1 : modules) {
                    if (module.getId() == module1.getParentId()){
                        child.add(module1);
                    }
                }
                adminModulesVo.setChild(child);
                modulesVos.add(adminModulesVo);
            }
        }
        return R.success(modulesVos);
    }
    /**
   /**
   *  根据管理员id 查询二级权限模块
   * @author wp
   * @param
   * @date 2023/1/13 19:35
   * @return
   */
    @GetMapping("/secondModules/{id}")
    public R getSecondModules(@PathVariable("id") long id){
        List<Long> secondModules = modulesService.getByIdSecondaryPermission(id);
        return R.success(secondModules);
    }
    /**
    * 根据管理员的id 修改管理员的模块权限
    * @author wp
    * @param
    * @date 2023/1/13 20:07
    * @return
    */
    @PutMapping("/modules/{id}")
    public R updatePermission(@PathVariable("id") long id,@RequestParam("moduleIds") String moduleIds){
        Boolean isTrue = modulesService.updatePermission(id, moduleIds);
        redisTemplate.delete("auth:"+id);
        if (isTrue)
        return R.success("权限更新成功");
        else
        return R.error("权限更新失败");
    }
    /**
    * 根据管理员的id修改其状态
    * @author wp
    * @param id 管理员id
    * @dupdateByUserate 2023/1/13 21:34
    * @return
    */
    @PutMapping("/{id}")
    public R updateAdminState(@RequestParam("state") int state,@PathVariable("id") long id){
        Admin admin = adminService.getById(id);
        admin.setState(state==1 ? 0:1);
        boolean isTrue = adminService.updateById(admin);
        if (isTrue)
            return R.success("状态修改成功");
        else
            return R.error("状态修改失败");
    }
    /**
    * 添加管理员
    * @author wp
    * @param
    * @date 2023/1/13 22:16
    * @return
    */
    @PostMapping()
    public R addAdmin(@RequestBody Admin admin){
        // 密码使用md5加密
        String password = admin.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        admin.setPassword(password);
        boolean isTrue = adminService.save(admin);
        if (isTrue)
            return R.success("添加成功");
        else
            return R.error("添加失败");
    }
    /**
    *修改管理员
    * @author wp
    * @param
    * @date 2023/1/13 22:17
    * @return
    */
       @PutMapping()
        public R updateAdmin(@RequestBody Admin admin){
           System.out.println(admin);
           boolean isTrue = adminService.updateById(admin);
           if (isTrue)
               return R.success("修改成功");
           else
               return R.error("修改失败");
        }
        /**
        * 根据id删除管理员
        * @author wp
        * @param  id
        * @date 2023/1/13 23:04
        * @return
        */
      @GetMapping("/{id}")
      public  R getByIdAdmin(@PathVariable("id") long id){
           return R.success(adminService.getById(id));
        }
    @DeleteMapping("/{id}")
    @Transactional
    public  R deleteByIdAdmin(@PathVariable("id") long id){
          // 删除外键关系列表 管理员模块关系表
         adminMapper.byAdminIdDelete(id);
        boolean isTrue = adminService.removeById(id);
        if (isTrue)
            return R.success("删除成功");
        else
            return R.error("删除失败");
    }
    /**
     * 获取证书类型列表
     * @author wp
     * @param
     * @date 2023/1/14 10:36
     * @return
     */
    @GetMapping("/certifyTypes/{page}/{pageSize}")
    public R getCertifyTypes(@PathVariable("page") int page,@PathVariable("pageSize") int pageSize){
        // 分页构造器
        Page<CertifyType> pageInfo= new Page<>(page,pageSize);
        certifyTypeService.page(pageInfo);
        return R.success(pageInfo);
    }
    /**
     * 根据证书类型id获取证书
     * @author wp
     * @param id
     * @date 2023/1/14 11:07
     * @return
     */
    @GetMapping("/certifyTypes/{id}")
    public R  byIdCertifyType(@PathVariable("id") long id){
        return R.success(certifyTypeService.getById(id));
    }
    /**
     * 添加证书类型
     * @author wp
     * @param
     * @date 2023/1/14 11:16
     * @return
     */
    @PostMapping("/certifyType")
    public R addCertifyType(@RequestBody CertifyType certifyType){
        LambdaQueryWrapper<CertifyType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!StrUtil.hasBlank(certifyType.getName()),CertifyType::getName,certifyType.getName());
        List<CertifyType> list = certifyTypeService.list(queryWrapper);
        if (list.size()>0) {
            return R.error("已有该证书类型");
        }
        boolean isTrue = certifyTypeService.save(certifyType);
            if (isTrue)
                return R.success("添加成功");
            else
                return R.error("添加失败");

    }
    @PostMapping("/community")
    public R addCommunity(@RequestBody BelongCommunity belongCommunity){
        LambdaQueryWrapper<BelongCommunity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!StrUtil.hasBlank(belongCommunity.getCommunity()),BelongCommunity::getCommunity,belongCommunity.getCommunity());
        List<BelongCommunity> list = belongCommunityService.list(queryWrapper);
        if (list.size()>0) {
            return R.error("已有该社区");
        }
        boolean isTrue = belongCommunityService.save(belongCommunity);
        if (isTrue)
            return R.success("添加成功");
        else
            return R.error("添加失败");

    }
    /**
     *  修改证书类型信息
     * @author wp
     * @param
     * @date 2023/1/14 11:19
     * @return
     */
    @PutMapping("/certifyType")
    public R updateCertifyType(@RequestBody CertifyType certifyType){
        boolean isTrue = certifyTypeService.updateById(certifyType);
        if (isTrue)
            return R.success("修改成功");
        else
            return R.error("修改失败");
    }
    @PutMapping("/community")
    public R updateCommunity(@RequestBody BelongCommunity belongCommunity){
        boolean isTrue = belongCommunityService.updateById(belongCommunity);
        if (isTrue)
            return R.success("修改成功");
        else
            return R.error("修改失败");
    }
    /**
     * 根据证书类型id删除证书类型
     * @author wp
     * @param id
     * @date 2023/1/14 11:21
     * @return
     */
    @DeleteMapping("/certifyType/{id}")
    @Transactional
    public R deleteCertifyType(@PathVariable("id") long id){
        //删除大类型下面的 子证书
        LambdaQueryWrapper<Certify> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Certify::getTypeId,id);
        List<Certify> list = certifyService.list(queryWrapper);
        if (list.size()>0){
            return R.error("该类证书类型绑定有子类证书,请删除子类证书");
        }
        boolean isTrue = certifyTypeService.removeById(id);
        if (isTrue)
            return R.success("删除成功");
        else
            return R.error("删除失败");
    }


    /**
     * 获取证书列表
     * @author wp
     * @param page
     * @param pageSize
     * @date 2023/1/14 13:07
     * @return
     */
    @GetMapping("/certify/{page}/{pageSize}")
    public R getCertifyList(@PathVariable("page") int page,
                            @PathVariable("pageSize") int pageSize,
                            @RequestParam("certifyTypeId") String certifyTypeId,
                            @RequestParam("certifyName") String certifyName){
        Page<CertifyVO>  certifyVoPage=new Page<>();
        Page<Certify> pageInfo= new Page<>(page,pageSize);
        // 根据证书名称查找
        LambdaQueryWrapper<Certify> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StrUtil.isBlank(certifyName),Certify::getName,certifyName);
        // 根据类型查找
        queryWrapper.eq(!StrUtil.isBlank(certifyTypeId),Certify::getTypeId,certifyTypeId);
        // 分页查询
        certifyService.page(pageInfo,queryWrapper);
        // 封装自定义page
        BeanUtil.copyProperties(pageInfo,certifyVoPage,"records");
        // 封装自定义的records
        List<Certify> records=pageInfo.getRecords();

        List<CertifyVO> list=records.stream().map((item)->{
            CertifyVO certifyVo = new CertifyVO();

            BeanUtil.copyProperties(item,certifyVo);
            Long typeId = item.getTypeId();
            CertifyType certifyType = certifyTypeService.getById(typeId);
            if (certifyType!=null){
                String name = certifyType.getName();
                certifyVo.setType(name);
                System.out.println(name);
            }
            return certifyVo;
        }).collect(Collectors.toList());

        certifyVoPage.setRecords(list);
        return R.success(certifyVoPage);
    }
    /**
     * 添加证书
     * @author wp
     * @param
     * @date 2023/1/14 15:05
     * @return
     */
    @PostMapping("/certify")
    public R addCertify(@RequestBody Certify certify){
        boolean isTrue = certifyService.save(certify);
        if (isTrue)
            return R.success("添加成功");
        else
            return R.error("添加失败");
    }
    /**
     * 根据证书id获取证书对象
     * @author wp
     * @param
     * @date 2023/1/14 15:05
     * @return
     */
    @GetMapping("/certify/{id}")
    public R byIdCertify(@PathVariable("id") long id){
        return R.success(certifyService.getById(id));
    }
    /**
     * 修改证书
     * @author wp
     * @param
     * @date 2023/1/14 15:05
     * @return
     */
    @PutMapping("/certify")
    public R updateCertify(@RequestBody Certify certify){
        boolean isTrue = certifyService.updateById(certify);
        if (isTrue)
            return R.success("修改成功");
        else
            return R.error("修改失败");
    }
    /**
     * 根据证书id删除特长
     * @author wp
     * @param
     * @date 2023/1/14 15:05
     * @return
     */
    @DeleteMapping("/certify/{id}")
    public R deleteCertify(@PathVariable("id") long id){
        LambdaQueryWrapper<RUserCertify> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(RUserCertify::getCertifyId,id);
        List<RUserCertify> list = rUserCertifyService.list(queryWrapper);
        if (list.size()>0){
            return R.error("该证书下面绑定有志愿者,请先删除该证书下面的所有绑定的志愿者");
        }
        boolean isTrue = certifyService.removeById(id);
        if (isTrue)
            return R.success("删除成功");
        else
            return R.error("删除失败");
    }

    /**
     * 获取特长类型列表
     * @author wp
     * @param
     * @date 2023/1/14 10:36
     * @return
     */
    @GetMapping("/specialityTypes/{page}/{pageSize}")
    public R getSpecialityTypes(@PathVariable("page") int page,@PathVariable("pageSize") int pageSize){
        // 分页构造器
        Page<SpecialityType> pageInfo= new Page<>(page,pageSize);
        specialityTypeService.page(pageInfo);
        return R.success(pageInfo);
    }
    //获取社区列表
    @GetMapping("/getCommunityList/{page}/{pageSize}")
    public R getCommunityList(@PathVariable("page") int page,@PathVariable("pageSize") int pageSize){
        // 分页构造器
        Page<BelongCommunity> pageInfo= new Page<>(page,pageSize);
        belongCommunityService.page(pageInfo);
        return R.success(pageInfo);
    }
    /**
     * 根据特长类型id获取特长类型
     * @author wp
     * @param id
     * @date 2023/1/14 11:07
     * @return
     */
    @GetMapping("/specialityTypes/{id}")
    public R  byIdSpecialityTypes(@PathVariable("id") long id){
        return R.success(specialityTypeService.getById(id));
    }
    @GetMapping("/community/{id}")
    public R  byIdCommunity(@PathVariable("id") long id){
        return R.success(belongCommunityService.getById(id));
    }
    /**
     * 添加特长类型
     * @author wp
     * @param
     * @date 2023/1/14 11:16
     * @return
     */
    @PostMapping("/specialityType")
    public R addSpecialityType(@RequestBody SpecialityType specialityType){
        LambdaQueryWrapper<SpecialityType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!StrUtil.hasBlank(specialityType.getName()),SpecialityType::getName,specialityType.getName());
        List<SpecialityType> list = specialityTypeService.list(queryWrapper);
        if (list.size()>0) {
            return R.error("已有该特长类型");
        }
        boolean isTrue = specialityTypeService.save(specialityType);
        if (isTrue)
            return R.success("添加成功");
        else
            return R.error("添加失败");
    }
    /**
     *  修改特长类型信息
     * @author wp
     * @param
     * @date 2023/1/14 11:19
     * @return
     */
    @PutMapping("/specialityType")
    public R updateSpecialityType(@RequestBody SpecialityType specialityType){
        boolean isTrue = specialityTypeService.updateById(specialityType);
        if (isTrue)
            return R.success("修改成功");
        else
            return R.error("修改失败");
    }
    /**
     * 根据特长类型id 删除特长类型
     * @author wp
     * @param id
     * @date 2023/1/14 11:21
     * @return
     */
    @Transactional
    @DeleteMapping("/specialityType/{id}")
    public R deleteSpecialityType(@PathVariable("id") long id){
        //删除大类型下面的 子特长
        LambdaQueryWrapper<Speciality> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Speciality::getTypeId,id);
        List<Speciality> list = specialityService.list(queryWrapper);
        if (list.size()>0){
            return R.error("该特长大类下面绑定了子特长，请先删除子特长");
        }
        boolean isTrue = specialityTypeService.removeById(id);

        if (isTrue)
            return R.success("删除成功");
        else
            return R.error("删除失败");
    }
    @DeleteMapping("/community/{id}")
    public R deleteCommunity(@PathVariable("id") long id){
        boolean isTrue = belongCommunityService.removeById(id);
        if (isTrue)
            return R.success("删除成功");
        else
            return R.error("删除失败");
    }
    /**
     * 获取特长列表
     * @author wp
     * @param page
     * @param pageSize
     * @date 2023/1/14 13:07
     * @return
     */
    @GetMapping("/speciality/{page}/{pageSize}")
    public R getSpecialList(@PathVariable("page") int page,
                            @PathVariable("pageSize") int pageSize,
                            @RequestParam("specialityTypeId") String specialityTypeId,
                            @RequestParam("specialityName") String specialityName){
        log.info("----------------{}",specialityTypeId);
        Page<SpecialityVO>  specialityVoPage=new Page<>();
        Page<Speciality> pageInfo= new Page<>(page,pageSize);
        // 根据特性名称查找
        LambdaQueryWrapper<Speciality> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.like(!StrUtil.isBlank(specialityName),Speciality::getName,specialityName);
        // 根据类型查找
       queryWrapper.eq(!StrUtil.isBlank(specialityTypeId),Speciality::getTypeId,specialityTypeId);
        // 分页查询
        specialityService.page(pageInfo,queryWrapper);
        // 封装自定义page
        BeanUtil.copyProperties(pageInfo,specialityVoPage,"records");
        // 封装自定义的records
        List<Speciality> records=pageInfo.getRecords();
        List<SpecialityVO> list=records.stream().map((item)->{
            SpecialityVO specialityVo = new SpecialityVO();
            BeanUtil.copyProperties(item,specialityVo);
            Long typeId = item.getTypeId();
            SpecialityType specialityType = specialityTypeService.getById(typeId);
            if (specialityType!=null){
                String name = specialityType.getName();
                specialityVo.setType(name);
            }
            return specialityVo;
        }).collect(Collectors.toList());
        specialityVoPage.setRecords(list);
        return R.success(specialityVoPage);
    }
    /**
    * 添加特长
    * @author wp
    * @param
    * @date 2023/1/14 15:05
    * @return
    */
    @PostMapping("/speciality")
    public R addSpeciality(@RequestBody Speciality speciality){
        boolean isTrue = specialityService.save(speciality);
        if (isTrue)
            return R.success("添加成功");
        else
            return R.error("添加失败");
    }
    /**
     * 根据特长id获取特长对象
     * @author wp
     * @param
     * @date 2023/1/14 15:05
     * @return
     */
    @GetMapping("/speciality/{id}")
    public R byIdSpeciality(@PathVariable("id") long id){
            return R.success(specialityService.getById(id));
    }
    /**
     * 修改特长
     * @author wp
     * @param
     * @date 2023/1/14 15:05
     * @return
     */
    @PutMapping("/speciality")
    public R updateSpeciality(@RequestBody Speciality speciality){
        boolean isTrue = specialityService.updateById(speciality);
        if (isTrue)
            return R.success("修改成功");
        else
            return R.error("修改失败");
    }
    /**
     * 根据特长id删除特长
     * @author wp
     * @param
     * @date 2023/1/14 15:05
     * @return
     */
    @DeleteMapping("/speciality/{id}")
    public R deleteSpeciality(@PathVariable("id") long id){
        LambdaQueryWrapper<RUserSpeciality> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(RUserSpeciality::getSpecialityId,id);
        List<RUserSpeciality> list = rUserspecialityService.list(queryWrapper);
        if (list.size()>0){
            return R.error("该特长下面绑定有志愿者,请先删除该特长下面的所有绑定的志愿者");
        }
        boolean isTrue = specialityService.removeById(id);
        if (isTrue)
            return R.success("删除成功");
        else
            return R.error("删除失败");
    }

    /**
     * @param userDTO:
     * 用户自己修改信息
     * @return R
     * @author Sakura
     * @date 2023/3/8 15:29
     */
    @Transactional
    @PostMapping("/updateByUser")
    public R updateByUser(@RequestBody UserDTO userDTO){
//        System.out.println(userDTO);
        //如果证书列表位空，不需要审核，直接通过
        List<CertifyDTO> certify = userDTO.getCertify();
        if (certify.size()==0){
            User user=new User();
            BeanUtil.copyProperties(userDTO,user);
            int gender = IdcardUtil.getGenderByIdCard(userDTO.getIdCard());
            gender = gender==1?1:2;
            user.setSex(gender);
            int age = IdcardUtil.getAgeByIdCard(userDTO.getIdCard());
            user.setAge(age);
            boolean result = userService.updateById(user);
            if (!result){
                return R.error("修改失败，请重新尝试");
            }
            return R.success("修改成功");

        }
        //如果需要证书列表不为0，需要审核
        Messages messages=new Messages();
        messages.setDescription("志愿者添加证书审核");
        messages.setTime(new Date());
        messages.setState(0);
        messages.setType(1);
        messages.setIdKey(userDTO.getId());
        String key = CACHE_CERTIFY_KEY+userDTO.getId();

        //存到缓存中，然后
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(userDTO));

        boolean save = messagesService.save(messages);
        if (!save){
            return R.error("修改失败，请重新尝试");
        }

        return R.success("上传成功，等待管理员审核");
    }


    /**
     *
     * @author wp
     * @param
     * @date 2023/1/17 14:55
     * @return
     */
    @Transactional
    @PostMapping("/addOrUpdate")
    public R addUser(@RequestBody UserDTO userDTO,long adminId){

//        System.out.println(userDTO);
        Admin admin = adminService.getById(adminId);
        long uid = userDTO.getId();
        List<CertifyDTO> dtoCertify = userDTO.getCertify();
        List<SpecialityVO> dtoSpeciality = userDTO.getSpeciality();
        User user =new User();

        if (dtoCertify.size()==0&&dtoSpeciality.size()==0){
            user.setGrade("c");
        }else if (dtoCertify.size()==0&&dtoSpeciality.size()!=0){
            user.setGrade("b");
        }else if(dtoCertify.size()!=0){
            user.setGrade("a");
        }
        String idCard = userDTO.getIdCard();
//        String strYear = idCard.substring(6, 10);
//        Integer birYear = Integer.valueOf(strYear);
//
//        Date date = new Date();
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
//        String format = simpleDateFormat.format(date);
//        Integer nowYear = Integer.valueOf(format);
//        user.setAge(nowYear-birYear);
        int age = IdcardUtil.getAgeByIdCard(idCard);
        user.setAge(age);

        int sexNum = idCard.charAt(16);
        if (sexNum%2 == 0){
            user.setSex(2);
        }else {
            user.setSex(1);
        }


//        判断id是否为空，不为空就是修改
        if (uid!=0){
//            执行修改F
//            便于简单，修改新的我们可以将原来的关系删除，然后重新添加关系,
            user.setId(uid);
            user.setName(userDTO.getName());
            user.setEthnic(userDTO.getEthnic());
            user.setVocation(userDTO.getVocation());
            user.setComAddress(userDTO.getComAddress());
            user.setHomeAddress(userDTO.getHomeAddress());
//            这里的等级以后会改
//            user.setGrade("c");
            user.setIdCard(userDTO.getIdCard());
            user.setPhone(userDTO.getPhone());

            user.setCheckUser(admin.getName());
            user.setUpdateTime(new Date());

            boolean result = userService.updateById(user);

            if (!result){
                return R.error("修改失败，请重新尝试");
            }

            //这里需要将所有的人员关系删除，这里有一个bug，那就是如果数据库没有东西，则会删除失败
            boolean result2 = rUserTaskService.removeByUid(uid);

            boolean result3 = rUserSpecialityService.removeByUid(uid);

            boolean result4 = rUserCertifyService.removeByUid(uid);

            if (dtoCertify.size()==0&&dtoSpeciality.size()==0){
                return R.success("修改成功");
            }

            result = rUserCertifyService.addUserCertify(dtoCertify, uid,adminId);

            if (!result){
                return R.error("修改失败，请重新尝试");
            }

            result = rUserspecialityService.addUserSpeciality(dtoSpeciality, uid);

            if (!result){
                return R.error("修改失败，请重新尝试");
            }

            return R.success("修改成功");

        }else {
//             为0则执行添加,
           long millis = System.currentTimeMillis();
           user.setId(millis);
           user.setName(userDTO.getName());
           user.setEthnic(userDTO.getEthnic());
           user.setVocation(userDTO.getVocation());
           user.setComAddress(userDTO.getComAddress());
           user.setHomeAddress(userDTO.getHomeAddress());
           user.setIdCard(userDTO.getIdCard());
           user.setPhone(userDTO.getPhone());

           user.setCheckUser(admin.getName());
           user.setRegTime(new Date());
           user.setUpdateTime(new Date());
            boolean result = userService.save(user);

            if (!result){
                return R.error("添加失败，请重新尝试");
            }

            if (dtoCertify.size()==0&&dtoSpeciality.size()==0){
                return R.success("添加成功");
            }
//

//           添加的话肯定全都是添加特长,没用不存在的人持有证书和特长
            result = rUserCertifyService.addUserCertify(dtoCertify, millis,adminId);

            if (!result){
                return R.error("添加失败，请重新尝试");
            }

            result = rUserspecialityService.addUserSpeciality(dtoSpeciality, millis);

            if (!result){
                return R.error("添加失败，请重新尝试");
            }

            return R.success("添加成功");
        }

    }

    @Transactional
    @PostMapping("/agreeMsg/{aid}/{mid}/{uid}")
    public R agreeCertifyMessage(@RequestBody UserDTO userDTO,
                                 @PathVariable("aid") long aid,
                                 @PathVariable("mid") long mid,
                                 @PathVariable("uid") long uid){
//        System.out.println(userDTO);
//        System.out.println(aid);
//        System.out.println(mid);
//        System.out.println(uid);
        Admin admin = adminService.getById(aid);
        R r = addUser(userDTO, aid);
        if (!r.isStatus()){
            return R.error("处理失败，请稍后再尝试");
        }
        Messages messages = messagesService.getById(mid);
        messages.setState(1);
        boolean result = messagesService.updateById(messages);
        if (!result){
            return R.error("处理失败，请稍后再尝试");
        }

        Messages toUser=new Messages();
        toUser.setState(0);
        toUser.setType(3);
        toUser.setIdKey(uid);
        toUser.setTime(new Date());
        toUser.setDescription("证书审核已经通过");
        result = messagesService.save(toUser);
        if (!result){
            return R.error("处理失败，请稍后再尝试");
        }
//        redisTemplate.delete(CACHE_CERTIFY_KEY+uid);

        return R.success("处理成功");
    }

    @PostMapping("/updatePwd/{aid}")
    public R updatePassword(@PathVariable("aid") long aid,
                            @RequestBody UpdateDTO updateDTO){
//        System.out.println(aid);
        if (!updateDTO.getNewPassword().equals(updateDTO.getReNewPassword())){
            return R.error("两次密码不一致，请重新输入");
        }
        Admin admin = adminService.getById(aid);
        if (!(updateDTO.getOldPassword().equals(admin.getPassword()))){
            return R.error("原密码错误，请重新输入");
        }
        admin.setPassword(updateDTO.getNewPassword());
        boolean update = adminService.updateById(admin);
        if (!update){
            return R.error("修改失败，请重新尝试");
        }
//        System.out.println(updateDTO);
        return R.success("修改成功");
    }

    /**
    *
    * @author wp
    * @param
    * @date 2023/3/20 16:06
    * @return
    */
    /**
     * 批量添加人员
     * @return
     */
    @PostMapping("/import/{adminId}")
    public R importUser(@PathVariable long adminId , MultipartFile file){
        Admin admin = adminService.getById(1);
        int count = 0;
        try {
            InputStream inputStream = file.getInputStream();
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = xssfWorkbook.getSheetAt(0);

            int lastRowNum = sheet.getLastRowNum();
            for (int i = 1; i < lastRowNum + 1; i++) {
                XSSFRow row = sheet.getRow(i);
                if (row != null){
                    List<String> stringList = new ArrayList<>();
                    for (Cell cell : row) {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String value = cell.getStringCellValue();
                        if (value == ""){
                            stringList.add("空");
                        } else {
                            stringList.add(value);
                        }
                    }
                    if (stringList.size() > 0){
                        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(User::getPhone,stringList.get(6));
                        User one = userService.getOne(queryWrapper);
                        if (one == null){
                            User user = new User();
                            long millis = System.currentTimeMillis();
                            user.setId(millis);
                            user.setName(stringList.get(0));
                            user.setEthnic(stringList.get(1));
                            user.setVocation(stringList.get(2));
                            user.setComAddress(stringList.get(3));
                            user.setHomeAddress(stringList.get(4));
                            user.setIdCard(stringList.get(5));
                            user.setPhone(stringList.get(6));

                            String idCard = user.getIdCard();

                            String strYear = idCard.substring(6, 10);
                            Integer birYear = Integer.valueOf(strYear);
                            Date date = new Date();
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
                            String format = simpleDateFormat.format(date);
                            Integer nowYear = Integer.valueOf(format);
                            user.setAge(nowYear-birYear);

                            int sexNum = idCard.charAt(16);
                            if (sexNum%2 == 0){
                                user.setSex(2);
                            }else {
                                user.setSex(1);
                            }

                            user.setCheckUser(admin.getName());
                            user.setRegTime(new Date());
                            user.setUpdateTime(new Date());
                            boolean result = userService.save(user);
                            if (!result){
                                return R.error("第"+count+"人员添加失败存在数据问题，后续人员添加终止");
                            }
                        }
                        count++;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("批量添加失败");
        }
        return R.success("批量添加成功");
    }
    /**
    *  根据管理员的id 重置管理员的密码
    * @author wp
    * @param
    * @date 2023/3/21 16:37
    * @return
    */
    @PutMapping("/resetPwd/{id}")
    public  R resetPwd(@PathVariable("id") long id){
        Admin admin = adminService.getById(id);
        if ( admin != null){
            String pwd= MD5.create().digestHex("123456");
            admin.setPassword(pwd);
            boolean isTrue = adminService.updateById(admin);
            if (isTrue){
                return R.success("重置密码成功");
            }
            return R.error("重置密码错误");
        }
        return R.error("该管理员不存在");
    }

}
